package org.sample.jdbc;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.sample.jdbc.commons.jdbc.DalClient;
import org.sample.jdbc.commons.jdbc.PoolDalClient;

/**
 * Created by Alan.ye on 2016/10/5.
 */
public class Application {

    public static void main(String[] args) throws Exception {
        singleTask();
        multipleTask();
    }

    private static void singleTask() {
        DalClient source = new PoolDalClient("source");
        DalClient target = new PoolDalClient("target");

        long startTime = System.currentTimeMillis();

        importLog(source, target);

        long endTime = System.currentTimeMillis();
        System.out.println((endTime - startTime) / 1000);
    }

    private static void multipleTask() throws InterruptedException {
        DalClient source = new PoolDalClient("source");
        DalClient target = new PoolDalClient("target");

        ExecutorService pool = Executors.newFixedThreadPool(4);

        long startTime = System.currentTimeMillis();

        pool.execute(() -> importLog(source, target));

        pool.shutdown();
        pool.awaitTermination(2, TimeUnit.DAYS);
        long endTime = System.currentTimeMillis();
        System.out.println((endTime - startTime) / 1000);
    }


    private static void importLog(DalClient source, DalClient target) {
        String name = "Log";
        try {
            target.begin();
            source.foreach(entity -> {
                convert(entity);
                System.out.println(entity.length + Arrays.toString(entity));

                target.insert("insert" + name, entity);
                return false;
            }, "find" + name);

            target.commit();
        } catch (SQLException e) {
            target.rollback();
            e.printStackTrace();
        }
    }

    private static void convert(Object[] entity) {
        for (int i = 0; i < entity.length; i++) {
            Object o = entity[i];
            if (o instanceof BigDecimal)
                entity[i] = ((BigDecimal) o).intValue();
        }
    }
}